<template>
  <web-view
    v-if="isRender"
    :src="src"
    :update-title="updateTitle"
    :webview-styles="webviewStyles"
    allow="*"
    @message="onMessage"
    @load="onLoaded"
  ></web-view>
</template>

<script>
import qs from 'query-string'
import omit from 'lodash-es/omit'
import config from '@/config.js'

function getTimestamp() {
  return new Date().getTime()
}

export default {
  data() {
    const uniPlatform = uni.getSystemInfoSync().uniPlatform

    return {
      baseURL: config.linkURL,
      updateTitle: true,
      webviewStyles: {
        progress: true,
        color: '#ea0014',
      },
      params: {
        path: '',
        query: {
          /**
           * 页面模式
           * single 外部网页内部打开的页面将由网页内部自己处理
           * multiple 外部网页内部打开页面时将会使用 uniapp 的 webview 重新创建一个
           */
          pageMode: 'single',
          // 页面标题:
          title: '',
          // 当前平台: 一般不需要自定义 打开外部网页时会自动带入
          platform: ['uniapp', uniPlatform].join('-'),
          // 自动刷新: 重新回到该页面时会自动刷新页面 1 开启 2 关闭
          autoRefresh: '0',
          // 时间戳：用于防止页面缓存
          timestamp: getTimestamp(),
          // 是否使用 loading
          showLoading: '0',
        },
      },
      onShowFlag: false,
      isRender: true,
    }
  },
  computed: {
    src() {
      if (!this.params.path) {
        return ''
      }

      const getPath = () => {
        const value = this.params.path
        return value.startsWith('http') ? value : this.baseURL + value
      }

      const query = omit(this.params.query, ['autoRefresh'])

      const value = `${getPath()}?${qs.stringify(query)}`

      return value
    },
    autoRefresh() {
      return this.params.query.autoRefresh === '1'
    },
    showLoading() {
      return this.params.query.showLoading === '1'
    },
  },
  onShow() {
    if (!this.onShowFlag) {
      this.onShowFlag = true
      return false
    }

    if (this.autoRefresh) {
      this.reRender()
    }
  },
  onLoad(params) {
    const path = this.$tools.parse(params.path)
    const query = this.$tools.parse(params.query)

    console.log('webview.onLoad.path', path)
    console.log('webview.onLoad.query', query)

    this.params = {
      path,
      query: {
        ...this.params.query,
        ...query,
      },
    }

    if (this.showLoading) {
      uni.showLoading({ title: 'Loading' })
    }
  },
  mounted() {
    // #ifndef MP */
    this.onLoaded()
    // #endif
  },
  methods: {
    onMessage(event) {
      const data = event?.detail?.data || []
      uni.$emit('on-webview-message', data)
    },
    async reRender() {
      this.isRender = false
      await this.$nextTick()
      this.isRender = true
    },
    async onLoaded() {
      uni.hideLoading()

      const title = this.params?.query?.title

      if (title) {
        uni.setNavigationBarTitle({
          title,
        })
      }
    },
  },
}
</script>

<style></style>
